import java.sql.*
import groovy.json.JsonOutput

/**
 * 使用Groovy SQL模块将Jenkins构建结果存储到MySQL数据库
 * @param config 配置参数，可覆盖默认数据库连接信息
 */
@NonCPS
def saveBuildResult() {
    // 从资源文件加载默认配置
    def defaultConfig = loadResourceConfig()
    // 构建结果数据
    def buildData = collectBuildData()
    println "Collected build data: ${buildData}"
    // 使用Groovy SQL模块保存数据
    saveToDatabase(defaultConfig, buildData)
}

/**
 * 使用Groovy SQL保存数据到数据库
 */
@NonCPS
private void saveToDatabase(Map config, Map buildData) {
    try {
        def conn = DriverManager.getConnection(config.url, config.username, config.password)
        def stmt = conn.prepareStatement('''
            INSERT INTO le_jenkins_results (
                job_name, build_number, result, 
                duration, start_time, end_time, 
                parameters, created_by, canceled_by
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ''')

        stmt.setString(1, buildData.jobName)
        stmt.setInt(2, buildData.buildNumber)
        stmt.setString(3, buildData.result)
        stmt.setLong(4, buildData.duration)
        stmt.setTimestamp(5, buildData.startTime)
        stmt.setTimestamp(6, buildData.endTime)
        stmt.setString(7, buildData.parameters)
        stmt.setString(8, buildData.createdBy)
        stmt.setString(9, buildData.canceledBy)

        stmt.executeUpdate()
        println "Build result saved to database successfully."
    } catch (Exception e) {
        println "Failed to save build result to database: ${e.message}"
    }
}

/**
 * 收集构建数据
 */
@NonCPS
private Map collectBuildData() {
    def params = getBuildParameters()

    return [
        jobName: env.JOB_NAME,
        buildNumber: env.BUILD_NUMBER.toInteger(),
        result: currentBuild.currentResult,
        duration: currentBuild.duration ?: 0,
        startTime: new java.sql.Timestamp(currentBuild.startTimeInMillis),
        endTime: new java.sql.Timestamp(System.currentTimeMillis()),
        parameters: params.isEmpty() ? '{}' : JsonOutput.toJson(params),
        createdBy: getBuildUser(),
        canceledBy: getCancelUser()
    ]
}

/**
 * 从资源文件加载配置
 */
@NonCPS
private Map loadResourceConfig() {
    def configText = libraryResource('config/db.json')
    def jsonSlurper = new groovy.json.JsonSlurper()
    def config = jsonSlurper.parseText(configText)
    println "Database configuration: ${config}"
    
    return config
}

/**
 * 获取构建参数
 */
@NonCPS
private Map getBuildParameters() {
    def parameters = [:]
    def build = currentBuild.rawBuild
    
    // 获取参数化构建的参数
    if (build.getAction(ParametersAction)) {
        build.getAction(ParametersAction).getParameters().each { param ->
            parameters[param.getName()] = param.getValue()?.toString() ?: 'null'
        }
    }
    
    return parameters
}

/**
 * 获取启动构建的用户
 */
@NonCPS
private String getBuildUser() {
    def cause = currentBuild.rawBuild.getCause(hudson.model.Cause.UserIdCause)
    return cause?.getUserName() ?: 'unknown'
}

/**
 * 获取取消构建的用户（如果有）
 */
@NonCPS
private String getCancelUser() {
    // 仅当构建结果为ABORTED时才尝试获取取消用户
    if (currentBuild.currentResult != 'ABORTED') {
        return ""
    }

    def actions = currentBuild.rawBuild.getActions()
    
    for (action in actions) {
        if (action instanceof hudson.model.CauseAction) {
            def causes = action.getCauses()
            for (cause in causes) {
                if (cause instanceof hudson.model.Cause.UserIdCause) {
                    return cause.getUserName()
                }
            }
        }
    }
    
    return null
}    